//
//  ZLCourseLerningDetailViewController.m
//  ZLExamination
//
//  Created by Zheng on 2017/8/15.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "ZLCourseLerningDetailViewController.h"

#import "ZLCourseLearningDetailCell.h"
#import "ZLLearnSelectionViewController.h"
#import "ZLTogetherLearnModel.h"
#import "ZLCourseLearningDetailHeaderView.h"
#import "ZLCourseLerningDetailModel.h"
#import "ZLExamBeginViewController.h"
#import "ZLBaseNavigationController.h"
#import "ZLLearnSelectionVideoViewController.h"

#import "ZLExamResultViewController.h"

@interface ZLCourseLerningDetailViewController ()

@property (nonatomic, strong) ZLCourseLearningDetailHeaderView *headerView;
@property (nonatomic, strong) ZLCourseLerningDetailModel *detailModel;

@end

@implementation ZLCourseLerningDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.myTableView.backgroundColor = [UIColor whiteColor];
    
    self.headerView = ({
        ZLCourseLearningDetailHeaderView *headerView = [[ZLCourseLearningDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 180)];
        headerView;
    });
    
    self.myTableView.tableHeaderView = self.headerView;
    
    [self.myTableView registerClass:[ZLCourseLearningDetailCell class] forCellReuseIdentifier:kZLCourseLearningDetailListCell_ID];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
}

#pragma mark - 加载数据
- (void)loadData {
    
    NSDictionary *param = @{@"curriculum_id":_curriculum_id};
    
    [[YCRequestDataService sharedManager] Post:@"curriculum/curriculum/info" parameters:param success:^(id response) {
        if (response[@"error_code"]) {
            NSLog(@"%@",response[@"error_msg"]);
        } else {
            _detailModel = [[ZLCourseLerningDetailModel alloc] initWithDataDic:response[@"response_data"][@"lists"]];
            [self.myTableView reloadData];
            [self setDataForHeaderView];
        }
    } failure:^{
        NSLog(@"网络或服务器出错");
    }];
    
}

- (void)setDataForHeaderView {
    _headerView.progressValueLbl.text = [NSString stringWithFormat:@"%@%%",_detailModel.read_number];
//    _headerView.allValueLbl.text = [NSString stringWithFormat:@"共%@节课时",_detailModel.chapter_number];
    _headerView.timeValueLbl.text = [NSString stringWithFormat:@"%@/%@小时",_detailModel.the_read_time,_detailModel.read_time_length];
    
    if (_detailModel.paper_status.integerValue == 0) {
        //未开始
        _headerView.beginExamLbl.text = @"开始考试";
    } else if (_detailModel.paper_status.integerValue == 3) {
        //完成
        if (_detailModel.is_pass.integerValue == 1) {
            _headerView.beginExamLbl.text = @"考试合格, 查看成绩";
        } else if (_detailModel.is_pass.integerValue == 2) {
            _headerView.beginExamLbl.text = @"考试不合格, 重新考试";
        }
    } else {
        //继续
        _headerView.beginExamLbl.text = @"继续考试";
    }
    
#pragma mark 点击事件
    __weak typeof(self) weakSelf = self;
    
    _headerView.clickCallBack = ^(UILabel *label) {
        
        if ([label.text isEqualToString:@"开始考试"]) {
            kCX_LOG(@"开始考试");
            ZLExamBeginViewController *examBeginVC = [[ZLExamBeginViewController alloc] init];
            examBeginVC.actionStyle = ActionStyleBegin;
            examBeginVC.curriculum_id = @([weakSelf.detailModel.k_id intValue]);
            ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:examBeginVC];
            [weakSelf presentViewController:nav animated:YES completion:nil];
        } else if ([label.text isEqualToString:@"考试不合格, 重新考试"]) {
            kCX_LOG(@"考试不合格, 重新考试");
            
            ZLExamResultViewController *erVC = [[ZLExamResultViewController alloc] init];
            erVC.user_paper_id = weakSelf.detailModel.user_paper_id;
            erVC.curriculum_id = @([weakSelf.detailModel.k_id intValue]);
            ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:erVC];
            [weakSelf presentViewController:nav animated:YES completion:nil];

        } else if ([label.text isEqualToString:@"考试合格, 查看成绩"]) {
            kCX_LOG(@"考试合格, 查看成绩");
            ZLExamResultViewController *erVC = [[ZLExamResultViewController alloc] init];
            erVC.user_paper_id = weakSelf.detailModel.user_paper_id;
            ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:erVC];
            [weakSelf presentViewController:nav animated:YES completion:nil];
        
        } else if ([label.text isEqualToString:@"继续考试"]) {
            
            NSString *user_paper_id = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_paper_id"];
            
            if (user_paper_id) {
                NSDictionary *param = @{@"user_paper_id":user_paper_id};
                
                YCRequestDataService *manager = [YCRequestDataService sharedManager];
                [manager Post:@"paper/paper/sub_paper" parameters:param success:^(id response) {
                    if (!response[@"error_code"]) {
                        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"user_paper_id"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        
                        ZLExamBeginViewController *examBeginVC = [[ZLExamBeginViewController alloc] init];
                        examBeginVC.actionStyle = ActionStyleBegin;
                        examBeginVC.curriculum_id = @([weakSelf.detailModel.k_id intValue]);
                        ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:examBeginVC];
                        [weakSelf presentViewController:nav animated:YES completion:nil];
                    }
                } failure:^{
                    NSLog(@"网络或服务器出错");
                }];
            }
            
        }
    };

}


#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _detailModel.chapterList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZLCourseLearningDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:kZLCourseLearningDetailListCell_ID forIndexPath:indexPath];
    
    if (_detailModel.chapterList != 0) {
        cell.model = _detailModel.chapterList[indexPath.row];
    }
    
    return cell;
}

#pragma mark - tableview delegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    kCX_LOG(@"章节:%ld",indexPath.row);
    
    ZLCourseLerningDetailListModel *model = _detailModel.chapterList[indexPath.row];
    
    if (model.is_read.integerValue == 2) {
        //解锁 跳转学习
        
        if (model.type.integerValue == 1) {
            ZLLearnSelectionViewController *learnSelectionVC = [[ZLLearnSelectionViewController alloc] init];
            if (_detailModel.chapterList != 0) {
                learnSelectionVC.model = model;
            }
            
            [self.navigationController pushViewController:learnSelectionVC animated:YES];
        } else if (model.type.integerValue == 2) {
            //TODO:视频
            ZLLearnSelectionVideoViewController *lsvVC = [[ZLLearnSelectionVideoViewController alloc] init];
            if (_detailModel.chapterList != 0) lsvVC.model = model;
            [self.navigationController pushViewController:lsvVC animated:YES];
        }
        
        
    } else {
        //未解锁 提示
        NSString *title;
        
        if (model.status.integerValue == 1) {
            //未学习
            title = @"请先完成章节学习，章节学完后，才能进入练习";
        } else {
            if (model.exercises_status.integerValue != 4) {
                //练习未完成完成
                title = @"你还未完成课程学习和练习，全部完成后才能学习";
            }
        }
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        
        kDISPATCH_MAIN_THREAD(^{
            [self presentViewController:alert animated:YES completion:nil];
        });
        
    }
}



#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
